import React, { useState, useEffect } from 'react';
import { Divider, Button, Row, Col, Upload } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { getShopLogo, updateShopLogo } from '@/services/shop/api';
import { MsgType, replaceImgHost, showMsg, submitRichTextImgHost } from '@/utils/utils';
// @ts-ignore
import Cookies from 'js-cookie';
import {miniPro} from '@/utils/constants';
import PermissionControl from '@/components/PermissionControl';

const DecorateInfo: React.FC = () => {
  const [disabled, setDisabled] = useState<boolean>(true);
  const [uploadLogoLoading, setUploadLogoLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [shopLogoInfo, setShopLogoInfo] = useState<SHOPAPI.ShopLogo>({} as SHOPAPI.ShopLogo);
  const [logoFileList, setLogoFileList] = useState<any[]>([]);
  const [shopFileList, setShopFileList] = useState<any[]>([]);
  const [logoUrl, setLogoUrl] = useState<string>('');
  const [shopImageUrl, setShopImageUrl] = useState<string>('');
  const [postLoading, setPostLoading] = useState<boolean>(false);

  useEffect(() => {
    getShopLogo().then((data: SHOPAPI.ShopLogo) => {
      setShopLogoInfo(data);
      data.logo_url = replaceImgHost(data.logo_url || '');
      data.image_url = replaceImgHost(data.image_url || '');
      setLogoUrl(data.logo_url);
      setShopImageUrl(data.image_url);
      setLogoFileList([
        {
          url: data.logo_url
        }
      ]);
      setShopFileList([
        {
          url: data.image_url
        }
      ]);
    }).catch(error => {
      console.log(error)
      showMsg(error?.data?.errmsg);
    });
  }, []);

  const onPublish = async () => {
    try {
      const params = {
        logo_url: submitRichTextImgHost(logoFileList[0].url),
        image_url: submitRichTextImgHost(shopFileList[0].url)
      }
      if (!params.logo_url) {
        showMsg('请上传店铺Logo');
        return;
      }
      if (!params.image_url) {
        showMsg('请上传店铺形象');
        return;
      }
      if (postLoading) {
        return;
      }
      setPostLoading(true);
      await updateShopLogo(params);
      showMsg('已生效', MsgType.SUCCESS);
      setDisabled(true);
      setPostLoading(false);
    } catch (error) {
      setPostLoading(false);
      showMsg(error?.data?.errmsg);
    }
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
    </div>
  );

  const uploadLogoButton = (
    <div>
      {uploadLogoLoading ? <LoadingOutlined /> : <PlusOutlined />}
    </div>
  );

  // @ts-ignore
  const onLogoChange = ({file, fileList}) => {
    setLogoFileList(fileList);
    if (file.status === 'uploading') {
      setUploadLogoLoading(true);
    } else if (file.status === 'done') {
      setUploadLogoLoading(false);
      setLogoFileList([
        {
          url: replaceImgHost(miniPro + file.response[0].file_web_url)
        }
      ])
      setLogoUrl(replaceImgHost(miniPro + file.response[0].file_web_url));
    } else if (file.status === 'error') {
      setUploadLogoLoading(false);
      showMsg('文件上传失败');
    }
  }

  // @ts-ignore
  const onShopImageChange = ({file, fileList}) => {
    setShopFileList(fileList);
    if (file.status === 'uploading') {
      setLoading(true);
    } else if (file.status === 'done') {
      setLoading(false);
      setShopFileList([
        {
          url: replaceImgHost(miniPro + file.response[0].file_web_url)
        }
      ])
      setShopImageUrl(replaceImgHost(miniPro + file.response[0].file_web_url));
    } else if (file.status === 'error') {
      setLoading(false);
      showMsg('文件上传失败');
    }
  }

  return <div className="decorate-info">
     <div className="header">
       <div className="title">2.店铺装饰</div>
       <div className="btns">
       <PermissionControl action_id="600601003">
        <Button 
            style={{marginRight: "10px"}} 
            onClick={() => setDisabled(false)}
            type="primary">编辑</Button>
        </PermissionControl>
        <PermissionControl action_id="600601003">
         <Button type="primary" loading={postLoading} onClick={onPublish}>发布</Button>
        </PermissionControl>
      </div>
     </div>
    <Divider style={{margin: '10px 0'}} />
    <div className="info-body">
      <Row className="row">
        <Col span={4}>
          <Upload
            disabled={disabled}
            fileList={logoFileList}
            maxCount={1}
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            headers={{
              'Oper-Token': localStorage.getItem('Oper-Token')
            }}
            action="/api/common/file/batch/upload"
            onChange={onLogoChange}
            showUploadList={false}>
            { logoUrl ? <img src={logoUrl} style={{ width: '100%' }} /> : uploadLogoButton }
          </Upload>
          <div>
            {!disabled && <>点击上传店铺logo<br /></>}
            45 * 45
          </div>
        </Col>
        <Col span={4}>
          <Upload
            disabled={disabled}
            maxCount={1}
            fileList={shopFileList}
            name="file"
            listType="picture-card"
            className="shop-img"
            showUploadList={false}
            action="/api/common/file/batch/upload"
            headers={{
              'Oper-Token': localStorage.getItem('Oper-Token')
            }}
            onChange={onShopImageChange}>
            { shopImageUrl ? <img src={shopImageUrl} style={{ width: '100%', height: '100%' }} /> : uploadButton }
          </Upload>
          <div>
          {!disabled && <>点击更换店铺形象<br /></>}
            400 * 220
          </div>
        </Col>
      </Row>
    </div>
  </div>
}

export default DecorateInfo;